package com.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

/**
 * @author zhangs
 * @version v1.0
 * @decription 文件上传实战
 * @date 2021/3/24 21:19
 **/
@WebServlet(urlPatterns = "/demo08")
@MultipartConfig // 文件上传表单
public class Demo08 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 通过getPart(name)获取Part对象（name代表file文件域的name属性值）
        Part part = req.getPart("file");
        // 通过Part对象，获取上传的文件名
        String filename = part.getSubmittedFileName();
        // 获取上传文件需要存放的位置
        String realPath = req.getServletContext().getRealPath("/");
        // 将文件保存到指定位置
        part.write(realPath + filename);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
